//
//  ChargeViewController.m
//  ManageMoney
//
//  Created by epwk on 15/10/14.
//  Copyright © 2015年 db. All rights reserved.
//

#import "ChargeViewController.h"
#import "WebFileViewController.h"

@interface ChargeViewController ()
@property (weak, nonatomic) IBOutlet UITextField *moneyTextField;
@property (weak, nonatomic) IBOutlet UILabel *balanceLab;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *uvBottomCont;

@end

@implementation ChargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_moneyTextField becomeFirstResponder];
    [self setFieldNumberPad];
    
    
    
    self.balanceLab.text = [NSString stringWithFormat:@"%@   账户余额：%@ 元",_payChannelDic[@"channelSummary"],_payChannelDic[@"accountBalance"]];
    
    if (_chargeBool) {
        [self createRightBarButtonTitle:@"支付"];
        _moneyTextField.text = @"0";
        _moneyLabel.text = _moneyTextField.text;
        self.title = @"支付";
    }else{
        _moneyTextField.text = [NSString stringWithFormat:@"%@",CheckNull(_payChannelDic[@"accountBalance"])];
        [self createRightBarButtonTitle:@"提现"];
        _moneyLabel.text = _moneyTextField.text;
        self.title = @"提现";
    }
    
}



-(void)rightBarButtonClick:(UIButton *)btn
{
    
    if ([_moneyTextField.text length] == 0 || [_moneyTextField.text floatValue] == 0) {
        [self setFieldNumberPad];
        if (!_chargeBool) {
            [SVProgressHUD showErrorWithStatus:@"无法提现"];
        }
        [SVProgressHUD showErrorWithStatus:@"请输入充值金额"];
        
        return;
    }
    NSDictionary *params = [[NSDictionary alloc]init];
    params = @{@"tradeAmt":_moneyTextField.text,@"customerNum":_payChannelDic[@"customerNum"],@"channelNum":_payChannelDic[@"channelNum"]};
    
    if (_chargeBool) {
        [self requestChargeMoneyWithParams:params];  //充值
    }else
        [self requestTakeofMoneyWithParams:params];  //提现
    
    [self setFieldNumberPad];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setFieldNumberPad) name:AppToFront object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardDidHideNotification object:nil];
    _moneyTextField.secureTextEntry = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setFieldNumberPad
{
    _moneyTextField.keyboardType = UIKeyboardTypeDecimalPad;
    _moneyTextField.secureTextEntry = YES;
    _moneyTextField.text = @"0";
    _moneyLabel.text = _moneyTextField.text;
}



//键盘出现后，tableView相应的收缩
- (void)keyboardWillShow:(NSNotification *)notification
{
    _moneyTextField.secureTextEntry = NO;
    NSDictionary *kbInfo=[notification userInfo];
    //键盘的高度
    CGSize kbSize=[[kbInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0.3 animations:^{
        _uvBottomCont.constant=kbSize.height;
    }];

}

//键盘收起后，tableView相应的收缩
-(void)keyboardWillHidden:(NSNotification *)notification
{
    
    [UIView animateWithDuration:0.3 animations:^{
        _uvBottomCont.constant=0;
    }];
}



#pragma mark - textField delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if (!_chargeBool) {
//        return NO;
//    }
//    
//    NSString *myDotNumbers = @"0123456789.";
//    NSString *myNumbers = @"0123456789";
//    if (textField == _moneyTextField) {
//        NSCharacterSet *cs;
////        cs = [[NSCharacterSet characterSetWithCharactersInString:str] invertedSet];
////        NSString *filtered =
////        [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
////        BOOL basic = [string isEqualToString:filtered];
////        return basic;
//        
//        NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
//        if (NSNotFound == nDotLoc && 0 != range.location) {
//            cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers] invertedSet];
//        }
//        else {
//            cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers] invertedSet];
//        }
//        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
//        BOOL basicTest = [string isEqualToString:filtered];
//        if (!basicTest) {
//            
////            [self showMyMessage:@"只能输入数字和小数点"];
//            return NO;
//        }
//        if (NSNotFound != nDotLoc && range.location > nDotLoc + 3) {
//            return NO;
//        }
//
//        
//    }
//    
//    
//    return YES;
//    
//}

- (IBAction)valueChangeAction:(id)sender {
    UITextField *textField = (UITextField *)sender;
    if (textField.text.length > 1) {
        textField.text = [self getTheCorrectNum:textField.text];
    }
    _moneyLabel.text = _moneyTextField.text;
}

-(NSString*)getTheCorrectNum:(NSString*)tempString

{
    
    if ([tempString hasPrefix:@"0"])
        
    {
        if ([tempString rangeOfString:@"."].location != NSNotFound) {
            tempString = [tempString substringFromIndex:0];
        }else
            tempString = [tempString substringFromIndex:1];
        
        
    }
    
    return tempString;
    
}


#pragma mark - RequestAction 充值
-(void)requestChargeMoneyWithParams:(NSDictionary *)pramas
{
    
    
    [SVProgressHUD show];
    NSString *ChargeMoneyUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/recharge.do"];
    [HWHttpTool post:ChargeMoneyUrl params:pramas success:^(id json) {
        [SVProgressHUD dismiss];
        NSDictionary *dic = json;
        if ([dic[@"responseCode"] intValue] == 200) {
            
            WebFileViewController *ctr = [[WebFileViewController alloc] initWithNibName:@"WebFileViewController" bundle:nil];
            ctr.payId = dic[@"responseObj"][@"orderNo"];
            ctr.payBool = YES;
            [self.navigationController pushViewController:ctr animated:YES];
        }else
        {
            [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
    }];

}


#pragma mark - RequestAction
-(void)requestTakeofMoneyWithParams:(NSDictionary *)pramas
{
    
    [SVProgressHUD show];
    NSString *TakeofMoneyUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/cash.do"];
    [HWHttpTool post:TakeofMoneyUrl params:pramas success:^(id json) {
        [SVProgressHUD dismiss];
        NSDictionary *dic = json;
        if ([dic[@"responseCode"] intValue] == 200) {
            
            [SVProgressHUD showSuccessWithStatus:dic[@"responseMessage"]];
            [self leftBarButtonClick:nil];
            
        }else
        {
            [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
    }];
}




@end
